package util.utilitarioMail;

import Beans.OrderesController;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import util.utilitarioXML.XMLParser;

public class Email {

    public static void enviarEmail(List<String> emails, Properties props, String login, String senha, String assunto, String mensagem) {

        final List<String> e = emails;
        final Properties p = props;
        final String s = senha;
        final String l = login;
        final String a = assunto;
        final String m = mensagem;
         

        Thread email = new Thread() {

            @Override
            public void run() {
                Session session = Session.getDefaultInstance(p,
                        new javax.mail.Authenticator() {

                            @Override
                            protected PasswordAuthentication getPasswordAuthentication() {
                                return new PasswordAuthentication(l, s);
                            }

                        });

                session.setDebug(true);
                MimeMessage msg = new MimeMessage(session);

                try {

                    MimeMessage message = new MimeMessage(session);
                    message.setFrom(new InternetAddress(l));
                    if (e != null && !e.isEmpty()) {
                        String ends = "";

                        for (int i = 0; i < e.size() - 1; i++) {
                            ends += e.get(i) + ", ";
                        }
                        ends += e.get(e.size() - 1);

                        Address[] toUser = InternetAddress.parse(ends);

                        message.setRecipients(Message.RecipientType.TO, toUser);
                        message.setSubject(a);
                        message.setText(m);

                        Transport.send(message);
                    }
                }
                catch (MessagingException e) {
                    System.err.println(e);
                }
            }

        };
        email.start();
    }

    public static void enviarEmail(List<String> emails, String login, String senha, String assunto, String mensagem) {

        Properties props = new Properties();
        //propriedades de conexao com gmail..
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");

        enviarEmail(emails, props, login, senha, assunto, mensagem);
    }

    public static void enviarEmail(List<String> emails, String assunto, String mensagem) {

        Properties props = new Properties();
        //propriedades de conexao com gmail..
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");

        enviarEmail(emails, props, "ecommercexml@gmail.com", "3commercexml", assunto, mensagem);
    }

    public static void receberEmail() {

                try {
                    PropertiesMail ppm = new PropertiesMail();
                    Properties pp = System.getProperties();
                    pp.put("mail.pop.host", ppm.getHost());

                    Authenticator auth = new PopAuthentication();
                    Session session = Session.getDefaultInstance(pp, auth);

                    Store store = session.getStore("pop3s");
                    store.connect(ppm.getHost(), ppm.getAccountUser(), ppm.getAccountPassword());

                    Folder folder = store.getFolder("INBOX");
                    folder.open(Folder.READ_ONLY);

                    // Get directory
                    Message message[] = folder.getMessages();
                    System.out.println(folder.getMessageCount());

                    processMessage(message);

                    // Close connection 
                    folder.close(false);
                    store.close();
                }
                catch(Exception e) {
                    System.out.println(e.getMessage());
                }
//            }
//
//        };
//        email.start();
    }

    private static void processMessage(Message[] message) throws MessagingException, IOException {

        for (int i = 0; i < message.length; i++) {
            for (Message m : message) {
                Multipart multipart = (Multipart) m.getContent();
                // System.out.println(multipart.getCount());

                for (int j = 0; j < multipart.getCount(); j++) {
                    BodyPart bodyPart = multipart.getBodyPart(j);
                    if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {
                        continue; // dealing with attachments only
                    }

                    String ext = bodyPart.getFileName().substring(bodyPart.getFileName().lastIndexOf("."), bodyPart.getFileName().length());

                    if (ext.equals(".xml")) {

                        InputStream is = bodyPart.getInputStream();
                        File f = new File("C:\\XMLApplication\\src\\java\\config\\tmp\\" + bodyPart.getFileName());

                        FileOutputStream fos = new FileOutputStream(f);
                        byte[] buf = new byte[4096];
                        int bytesRead;

                        while ((bytesRead = is.read(buf)) != -1) {
                            fos.write(buf, 0, bytesRead);
                        }
                        fos.close();

                        //OrderesController.createOrder(XMLParser.parser(f)); >>>>>Acertar esse metodo
                    }
                }
            }
        }
    }

}
